<template>
    <div class="l-permit">
        <el-button-group class="l-permit-button">
            <el-button size="mini" type="primary" @click="createPermit()">新建权限组</el-button>
            <el-button size="mini" type="danger" @click="batchDel()">删除权限组</el-button>
        </el-button-group>
        <el-table type="selection" :data="tableData" border style="width: 100%">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index" width="50">
            </el-table-column>
            <el-table-column prop="rule_group_name" label="名称">
            </el-table-column>
            <el-table-column prop="rule_group_status" label="状态">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.rule_group_status" active-color="#409eff" inactive-color="#dfdfdf" :active-value="1" :inactive-value="2" @change="handlerState(scope.row)"/>
                </template>
            </el-table-column>
            <el-table-column prop="rule_group_addtime" label="时间">
                <template slot-scope="scope">
                    {{formatDate(scope.row.rule_group_addtime)}}
                </template>
            </el-table-column>
            <el-table-column prop="action" label="操作" width="180">
                <template slot-scope="scope">
                    <!-- <el-button size="small" @click="intLook(scope.row)">查看</el-button> -->
                    <el-button size="small" type="" @click="setUpdate(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="intDel(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 新建权限设置模态框 -->
        <el-dialog :title="dialog.title" :visible.sync="dialogVisible" :close-on-click-modal="false" class="dislog-permit">
            <div>
                <el-row type="flex">
                    <el-col :span="4" class="j-parmit-label">权限组名：</el-col>
                    <el-col :span="20">
                        <el-input style="width:300px;" v-model="permit.rule_group_name"  :disabled="page_state == 'see' ? true : false"  />
                    </el-col>
                </el-row>
                <el-row type="flex">
                    <el-col :span="4" class="j-parmit-label">是否启用：</el-col>
                    <el-col :span="20">
                        <el-radio-group v-model="permit.rule_group_status"  :disabled="page_state == 'see' ? true : false" >
                            <el-radio :label="1">启用</el-radio>
                            <el-radio :label="2">禁用</el-radio>
                        </el-radio-group>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="4" class="j-parmit-label">配置权限：</el-col>
                    <el-col :span="20">
                    	<el-scrollbar class="j-parmit-scrollbar" :native="false" :noresize="true">
                        <dl>
                            <template v-for="(item,index) in tree">
                                <dt>
                                    <el-checkbox v-model="item.checkbox" :disabled="page_state == 'see' ? true : false" :label="item.model_name" @change="handlerModule(index)">{{item.model_title}}</el-checkbox>
                                </dt>
                                <dd>
                                    <el-checkbox v-for="(cont,key) in item.children" :key="key" :disabled="page_state == 'see' ? true : false" v-model="cont.checkbox" :label="cont._id" @change="hanlderMethods()">{{ cont.rule_title }}</el-checkbox>
                                </dd>
                            </template>
                        </dl>
                        </el-scrollbar>
                    </el-col>
                </el-row>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" v-if="dialog.cancel" @click="dialogVisible = false">{{dialog.cancel}}</el-button>
                <el-button size="small" type="primary" @click="intAction()">{{dialog.determine}}</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script type="text/javascript">
import { get_rule_group_all,get_rule_list,rule_group_edit,rule_group_add,rule_group_del } from '@/api/permit'
export default {
    data() {
        return {
            dialogVisible: false,

            page_state:'add',
            // 	多条权限数组
            tableData: [],

            //单条权限组 
            permit: {

            },


            // 模态框配置
            dialog: {
                title: '新建权限组',
                cancel: '取消',
                determine: '确定',
            },

            // 权限树
            tree: [],

        }
    },
    watch:{

    },
    created() {

    },
    mounted(){
        console.log('路由传参',[{query:this.$route.query,params:this.$route.params}])


    	this.getPermitAll();
    },
    methods: {
    	/**
    	 * 直接表格中修改状态
    	 * @return {[type]} [description]
    	 */
    	handlerState(data){
    		rule_group_edit(data).then(response => {
			    this.$message({
		          message: '权限更新成功！',
		          type: 'success'
		        });
    		})
    	},


    	// 打开添加新的权限组模态框
        createPermit() {
        	this.dialog = {
                title: '新建权限组',
                cancel: '取消',
                determine: '确定',
            };
            this.permit = {};
        	this.page_state = 'add';
            this.dialogVisible = true;
            this.getTree();
        },

    	/**
    	 * 打开查看单条权限组模态框
    	 * @param  {[type]} data [description]
    	 * @return {[type]}      [description]
    	 */
    	async intLook(data){
            this.dialog = {
                title: '查看权限详情',
                cancel: '',
                determine: '关闭',
            };
    		this.page_state = 'see';

    		this.permit = data;
    		await this.getTree();
    		this.getSelectState();
    		this.dialogVisible = true;
    		// console.log('data',data);
    	},


    	/**
    	 * 打开更新单条权限组模态框
    	 * @param {[type]} data [description]
    	 */
    	async setUpdate(data){
    		this.dialog = {
                title: '更新权限详情',
                cancel: '取消',
                determine: '更新',
    		}
    		this.page_state = 'edit';
    		this.permit = JSON.parse(JSON.stringify(data));
    		await this.getTree();
    		this.getSelectState();
    		this.dialogVisible = true;
    		// console.log(data);
    	},

    	/**
    	 * 询问是否删除该权限设置
    	 * @return {[type]} [description]
    	 */
    	intDel(data){
    		this.permit = JSON.parse(JSON.stringify(data));
    		this.$confirm('此操作将永久删除该权限设置, 是否继续?', '系统提示', {
	          confirmButtonText: '继续',
	          cancelButtonText: '取消',
	          type: 'warning'
	        }).then(() => {
	        	this.delData();
	        }).catch(() => {
	          this.$message({
	            type: 'info',
	            message: '已取消删除'
	          });          
	        });
    	},

    	/**
    	 * 批量删除权限
    	 * @return {[type]} [description]
    	 */
    	batchDel(){
	        this.$message({
	          message: '批量删除正在开发中...',
	          type: 'warning'
	        });
    	},

    	/**
    	 * 区分模态框各类操作
    	 * @return {[type]} [description]
    	 */
    	intAction(){
    		switch(this.page_state){
    			// 添加
    			case "add":
    				this.addData();
    			break;
    			// 更新
    			case "edit":
    				this.updateData();
    			break;
   				default:
   					// 关闭模态框
   					this.dialogVisible = false;
    		}
    	},

    	/**
    	 * 获取所有权限组
    	 * @return {[type]} [description]
    	 */
    	getPermitAll(){
	    	get_rule_group_all().then(response => {
	    		this.tableData = response;
	    	})
    	},

    	/**
    	 * 
    	 * 访问API添加权限数据
    	 */
    	addData(){
    		if(!this.checkData()){ return false}
    		rule_group_add(this.permit).then(response => {
			    this.$message({
		          message: '添加权限成功！',
		          type: 'success'
		        });
		        this.dialogVisible = false;
		        this.getPermitAll();
    		})
    	},

    	/**
    	 * 访问API更新权限数据
    	 * @return {[type]} [description]
    	 */
    	updateData(){
    		if(!this.checkData()){ return false}
    		rule_group_edit(this.permit).then(response => {
			    this.$message({
		          message: '权限更新成功！',
		          type: 'success'
		        });
		        this.dialogVisible = false;
		        this.getPermitAll();
    		})
    	},

    	/**
    	 * 访问API删除权限数据
    	 * @return {[type]} [description]
    	 */
    	delData(){
    		rule_group_del(this.permit).then(response =>{
			    this.$message({
		          message: '权限删除成功！',
		          type: 'success'
		        });
		        this.getPermitAll();
    		})
    	},


    	// 判断必填事项
    	checkData(){
    		var tips = '';
    		var ret = false;
    		if(!this.permit.rule_group_name){
    			tips = "请输入权限名称！";
    			ret = true;
    		}else if(!this.permit.rule_group_status && this.permit.rule_group_status != 0){
    			tips = "请设置该权限是否激活！";
    			ret = true;
    		}else if(!this.permit.rule_group_rules){
    			tips = "请设置可访问选项";
    			ret = true;
    		}
    		if(ret){
			    this.$message({
		          message: tips,
		          type: 'warning'
		        });
			    return false;
    		}
    		return true;
    	},

        /**
         * 将时间戳转换为日期格式
         * @param  {[type]} value [description]
         * @return {[type]}       [description]
         */
        formatDate (value) { // 时间戳转换日期格式方法
           return new Date(parseInt(value)).toLocaleString().replace(/:\d{1,2}$/,' '); 
        },

    	/**
    	 * 获取所有权限树
    	 * @return {[type]} [description]
    	 */
    	async getTree(){
    		this.tree = [];
    		//访问api
    		await get_rule_list().then(response => {
    			this.tree = response
    		});

	    	/**
	    	 * 获取权限树，添加选择字段 checkbox
	    	 * @param  {[type]} item [description]
	    	 * @return {[type]}      [description]
	    	 */
	    	
	        this.tree.forEach(item => {
	        	item.children.forEach(cont => {
	        		this.$set(cont,'checkbox',false)
	        	})
	        	this.$set(item,'checkbox',false)
	        })
    	},

    	/**
    	 * 获取设置可访问的权限
    	 * @return {[type]} [description]
    	 */
    	getSelectState(){

	       	this.permit.rule_group_rules.forEach(id => {
	       		// 读取权限树中方法的id
	       		this.tree.forEach(item => {
		        	item.children.forEach(cont => {
		        		if(cont._id == id){
		        			this.$set(cont,'checkbox',true);
		        		}
		        	})
		        })
	       	})
	       	this.hanlderMethods();
    	},


        //检测子集中方法是否全部选中，设置模块全选状态
        hanlderMethods(){
        	this.permit.rule_group_rules = [];
        	this.tree.forEach(item => {
        		let select = true; 		//true 全选
        		item.children.forEach((cont,index) => {
        			if(!cont.checkbox){
        				select = false;
        			}else{
        				this.permit.rule_group_rules.push(cont._id);
        			}
        		})
        		this.$set(item,'checkbox',select)
        	})
        },

        //检测模块全选状态，设置子集中方法是否全部选中或不选中
        handlerModule(index){
        	this.permit.rule_group_rules = [];
        	let select = true  	//true 全选
        	if(this.tree[index].checkbox){
        		select = true
        	}else{
        		select = false
        	}
        	//设置子集方法选中状态
        	this.tree[index].children.forEach(item => {
        		this.$set(item,'checkbox',select)
        	})

        	this.hanlderMethods();
        }

    }
}
</script>
<style type="text/css" lang="scss">
.l-permit {
    .l-permit-button {
        margin-bottom: 10px;
    }

    dl,
    dd,
    dt {
        margin: 0px;
        padding: 0px;
    }

	.j-parmit-scrollbar{
    	width: 100%;
    	height: calc(100% - 100);
    	.el-scrollbar__wrap{
    		overflow-x:hidden;
    	}
    }
    .el-scrollbar:not(.el-menu--collapse){
    	min-height: 0px;
    }
    .el-scrollbar{
    	overflow: hidden;
    	overflow-y: auto 
    }
    
}

.el-row--flex {
    align-items: center;
    margin-bottom: 15px;

    &:last-child {
        margin-bottom: 0px;
    }
}

.dislog-permit {
    .el-checkbox__label {
        margin-bottom: 10px;
    }

    .j-parmit-label {
        text-align: right;
    }

    .j-parmit-scrollbar{
    	width: 100%;
    	max-height: 300px;
    	.el-scrollbar__wrap{
    		overflow-x:hidden;
    	}
    }
    .el-scrollbar:not(.el-menu--collapse){
    	min-height: 0px;
    }
    .el-scrollbar{
    	overflow: hidden;
    	overflow-y: auto 
    }
    dd {
        margin-left: 20px;
        margin-bottom: 10px;
    }
}
</style>